package ro.ubbcluj.cs.damate.plugin.ws.service;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.authentication.encoding.PasswordEncoder;
import org.springframework.ws.client.core.WebServiceTemplate;
import ro.ubbcluj.cs.damate.plugin.events.PluginEvent;
import ro.ubbcluj.cs.damate.plugin.utils.DateUtil;
import ro.ubbcluj.cs.damate.plugin.ws.generated.AuthenticationRequest;
import ro.ubbcluj.cs.damate.plugin.ws.generated.AuthenticationResponse;
import ro.ubbcluj.cs.damate.plugin.ws.generated.PluginEventRequest;
import ro.ubbcluj.cs.damate.plugin.ws.generated.PluginEventResponse;
import ro.ubbcluj.cs.damate.plugin.ws.generated.TokenValidationRequest;
import ro.ubbcluj.cs.damate.plugin.ws.generated.TokenValidationResponse;

public class WebServiceClient {

    private final WebServiceTemplate webServiceTemplate;

    @Autowired
    private transient PasswordEncoder passwordEncoder;

    public WebServiceClient(WebServiceTemplate template) {
        this.webServiceTemplate = template;
    }

    public int sendPluginEvent(PluginEvent event, String userToken) {
        PluginEventRequest request = RequestResponseBuilder.buildPluginEventRequest(event);
        request.setUser(userToken);
        request.setEventDate(DateUtil.isoDate(event.getDate().getTime()));
        PluginEventResponse response = (PluginEventResponse) webServiceTemplate.marshalSendAndReceive(request);
        return response.getResponseStatusCode();
    }

    public AuthenticationResponse authenticate(String username, String password) {
        AuthenticationRequest request = new AuthenticationRequest();
        request.setUsername(username);
        request.setPassword(passwordEncoder.encodePassword(password, null));
        return (AuthenticationResponse) webServiceTemplate.marshalSendAndReceive(request);
    }

    public boolean validateToken(String token) {
        TokenValidationRequest validationRequest = new TokenValidationRequest();
        validationRequest.setToken(token);
        return ((TokenValidationResponse) webServiceTemplate.marshalSendAndReceive(validationRequest)).isValid();
    }


}
